#include "shoppingcart_ui_logic.h"
#include "UserSession.h"
#include"globals.h"
ShoppingCartLogic* ShoppingCartLogic::instance = nullptr;
ShoppingCartLogic::ShoppingCartLogic(QObject *parent) : QObject(parent)
{
    // 初始化 UI 和其他资源
    ui = newBuyCart;

    setupProductData();
    connect(ui->checkoutButton,
            &QPushButton::clicked,
            this,
            &ShoppingCartLogic::onCheckoutButtonClicked);
}

void ShoppingCartLogic::setupProductData() {}

ShoppingCartLogic *ShoppingCartLogic::getInstance()
{
    if (!instance) {
        instance = new ShoppingCartLogic();
    }
    return instance;
}




void ShoppingCartLogic::addProductRow(const QPixmap &image, const QString &name, const QString &price, int productId, int quantity)
{
    QWidget *productWidget = new QWidget;  // Create a widget for each product row
    QHBoxLayout *productLayout = new QHBoxLayout(productWidget);

    QLabel *imageLabel = new QLabel;
    QLabel *nameLabel = new QLabel(name);
    QLabel *priceLabel = new QLabel(price);
    QSpinBox *quantitySpinBox = new QSpinBox;
    quantitySpinBox->setRange(1, 100);
    quantitySpinBox->setValue(quantity);
    QCheckBox *checkBox = new QCheckBox;
    QPushButton *removeButton = new QPushButton("删除");

    // Set the product image
    imageLabel->setPixmap(image.scaled(64, 64, Qt::KeepAspectRatio, Qt::SmoothTransformation));

    // Update quantity
    connect(quantitySpinBox, QOverload<int>::of(&QSpinBox::valueChanged), [=](int newQuantity)
            {
                checkBox->setProperty("productQuantity", newQuantity); // 更新商品数量
            });

    // Set product properties
    checkBox->setProperty("productName", name);
    checkBox->setProperty("productPrice", price);
    checkBox->setProperty("productQuantity", quantitySpinBox->value());
    checkBox->setProperty("productId", productId); // 存储商品 ID
    ui->checkboxes.append(checkBox);

    // Add widgets to the product layout
    productLayout->addWidget(imageLabel);
    productLayout->addWidget(nameLabel);
    productLayout->addWidget(priceLabel);
    productLayout->addWidget(quantitySpinBox);
    productLayout->addWidget(checkBox);
    productLayout->addWidget(removeButton);

    // Add product widget to the vertical layout
    ui->scrollArea->widget()->layout()->addWidget(productWidget);

    // Connect remove button signal
    connect(removeButton, &QPushButton::clicked, [this, productWidget]()
            {
                onRemoveButtonClicked(productWidget);  // Pass the product widget to the handler
            });
}

void ShoppingCartLogic::onRemoveButtonClicked(QWidget *productWidget)
{
    // Find the position of the widget within the layout
    QLayout *layout = ui->scrollArea->widget()->layout();
    int index = layout->indexOf(productWidget);

    if (index != -1) {
        // Remove the product widget from the layout
        layout->removeWidget(productWidget);
        productWidget->deleteLater();  // Safely delete the widget

        // Also remove the corresponding checkbox from the checkboxes list
        QCheckBox *checkBox = productWidget->findChild<QCheckBox *>();
        if (checkBox) {
            ui->checkboxes.removeOne(checkBox); // Remove the checkbox from the list
        }

        qDebug() << "已从购物车删除商品，行号:" << index;
    }

    // Refresh the layout
    layout->invalidate();  // Refresh the layout
    layout->update();      // Update the layout
}



void ShoppingCartLogic::onCheckoutButtonClicked()
{
    // Get selected items from the UI (scrollable list)
    QMap<QString, QStringList> selectedItems = ui->getSelectedItems();

    if (selectedItems.isEmpty())
    {
        QMessageBox::warning(nullptr, "提示", "未选中任何商品！");
        return;
    }

    qDebug() << "已勾选的商品:";

    PptpMessage requestMessage;
    QJsonObject parameters;

    // Ensure correct userId retrieval from UserSession
    int userId = UserSession::getInstance().getUserId();
    QJsonArray productIds;

    // Process selected items
    for (auto it = selectedItems.constBegin(); it != selectedItems.constEnd(); ++it)
    {
        QStringList values = it.value();

        if (values.size() < 3)
        {
            qDebug() << "商品数据不完整，跳过:" << it.key() << values;
            continue; // Skip incomplete data
        }

        QString name = it.key();  // Item name
        QString price = values.at(0);  // Item price
        QString quantity = values.at(1);  // Item quantity
        QString productId = values.at(2);  // Product ID

        qDebug() << "商品名称:" << name << ", 价格:" << price << ", 数量:" << quantity
                 << ", 商品ID:" << productId;

        QJsonObject productInfo;
        productInfo["product_id"] = productId.toInt();
        productInfo["quantity"] = quantity.toInt();
        productIds.append(productInfo);
    }

    if (productIds.isEmpty())
    {
        QMessageBox::warning(nullptr, "提示", "没有有效的商品被选中！");
        return;
    }

    // Send request to get address book
    PptpMessage addressRequest;
    addressRequest.setPath("user/getAddressBook");
    QJsonObject addressParams;
    addressParams["userId"] = userId;
    addressRequest.setParameters(addressParams);

    // Send request to the server
    pptpclient.pptpConnect(IP, PORT, addressRequest, this, &ShoppingCartLogic::onAddressResponse);
}

void ShoppingCartLogic::onAddressResponse(PptpMessage responseMessage)
{
    QJsonObject responseParameters = responseMessage.getParameters();
    QJsonArray addressBook = responseParameters["addressBook"].toArray();

    if (addressBook.isEmpty())
    {
        QMessageBox::information(nullptr, "提示", "暂无地址，请先添加地址");
        return;
    }

    // Create address selection dialog
    QDialog addressDialog;
    QVBoxLayout *layout = new QVBoxLayout(&addressDialog);

    QLabel *label = new QLabel("请选择收货地址：", &addressDialog);
    layout->addWidget(label);

    QComboBox *addressComboBox = new QComboBox(&addressDialog);

    for (const QJsonValue &value : addressBook)
    {
        QJsonObject address = value.toObject();
        QString displayText = QString("[%1] %2 (%3) - %4")
                                  .arg(address["label"].toString())
                                  .arg(address["name"].toString())
                                  .arg(address["phone"].toString())
                                  .arg(address["detailAddress"].toString());
        addressComboBox->addItem(displayText, address["addressId"].toInt());
    }

    layout->addWidget(addressComboBox);

    QPushButton *confirmButton = new QPushButton("确认", &addressDialog);
    layout->addWidget(confirmButton);

    // Confirm selection
    connect(confirmButton, &QPushButton::clicked, &addressDialog, &QDialog::accept);

    if (addressDialog.exec() == QDialog::Accepted)
    {
        // Get selected address
        int selectedAddressId = addressComboBox->currentData().toInt();
        this->selectedAddressId = selectedAddressId;  // Store selected address ID

        qDebug() << "已选择地址ID：" << selectedAddressId;

        // Retrieve selected items
        QMap<QString, QStringList> selectedItems = ui->getSelectedItems();
        QJsonArray productIds;

        for (auto it = selectedItems.constBegin(); it != selectedItems.constEnd(); ++it)
        {
            QJsonObject productInfo;
            productInfo["product_id"] = it.value().at(2).toInt();
            productInfo["quantity"] = it.value().at(1).toInt();
            productIds.append(productInfo);
        }

        // Continue processing after selecting address
        onAddressSelected(selectedAddressId, productIds);
    }
}
void ShoppingCartLogic::onAddressSelected(int addressId, const QJsonArray &productIds)
{
    QJsonObject finalRequest;
    finalRequest["user_id"] = UserSession::getInstance().getUserId();
    finalRequest["address_id"] = addressId;
    finalRequest["items"] = productIds;

    PptpMessage checkoutRequest;
    checkoutRequest.setPath("order/productBuy");
    checkoutRequest.setParameters(finalRequest);

    pptpclient.pptpConnect(IP, PORT, checkoutRequest, this, &ShoppingCartLogic::onBuyResponse);
}

void ShoppingCartLogic::onBuyResponse(PptpMessage responseMessage)
{
    QJsonObject responseParameters = responseMessage.getParameters();
    bool isOK = responseParameters.value("isOK").toBool();

    if (isOK)
    {

        newPage4->fetchOrderList();
        clearPurchasedItems(); // 清除已购买的商品
        qDebug() << "购买成功！";
    }
    else
    {
        QMessageBox::warning(nullptr, "提示", "购买失败！");
    }
}

void ShoppingCartLogic::clearPurchasedItems()
{
    QList<QWidget*> widgetsToRemove;  // To store widgets that need to be removed
    imgindex=0;
    indexlen = -1;
    // Iterate over each item in the vertical layout
    for (int i = 0; i < ui->verticalLayout->count(); ++i)
    {

        QLayoutItem *item = ui->verticalLayout->itemAt(i);
        if (item)
        {
            QWidget *widget = item->widget();
            if (widget)
            {
                // Check if the widget is a row containing a product with a checkbox
                qDebug() << "Checking widget at index:" << i;

                // Find the checkbox in the widget
                QCheckBox *checkBox = widget->findChild<QCheckBox*>();
                if (checkBox)
                {
                    qDebug() << "Checkbox found, is checked:" << checkBox->isChecked();
                    if (checkBox->isChecked())
                    {
                        widgetsToRemove.append(widget); // Mark widget for removal if checkbox is checked
                    }
                }
                else
                {
                    qDebug() << "No checkbox found in this widget";
                }
            }
        }
    }

    // Remove selected widgets
    for (QWidget *widget : widgetsToRemove)
    {
        qDebug() << "Removing widget:" << widget;

        // Remove from layout
        ui->verticalLayout->removeWidget(widget);

        // Remove from checkboxes list
        QCheckBox *checkBox = widget->findChild<QCheckBox*>();
        if (checkBox)
        {
            int index = ui->checkboxes.indexOf(checkBox);
            if (index != -1)
            {
                ui->checkboxes.removeAt(index);
            }
        }

        // Delete widget asynchronously
        widget->deleteLater();
    }

    // Re-layout the vertical layout to reflect the changes
    ui->verticalLayout->invalidate();
    ui->verticalLayout->update();
}


void ShoppingCartLogic::resetInstance()
{
    if (instance) {
        delete instance;
        instance = nullptr;
    }
}
ShoppingCartLogic::~ShoppingCartLogic() {

}
